package com.sec.etech.bpm.plugin.formfield.executer;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.sec.etech.bpm.groovy.EtechBpmScript;
import com.sec.etech.bpm.plugin.formfield.def.FormFieldUserPluginDef;
import com.sec.etech.org.service.EtechUserService;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.bpm.engine.plugin.runtime.abstact.AbstractUserCalcPlugin;
import org.openbpm.bpm.engine.plugin.session.BpmUserCalcPluginSession;
import org.openbpm.bpm.plugin.node.userassign.executer.UserAssignRuleCalc;
import org.openbpm.bus.api.model.IBusinessData;
import org.openbpm.org.api.model.IGroup;
import org.openbpm.org.api.model.IUser;
import org.openbpm.org.api.service.GroupService;
import org.openbpm.org.api.service.UserService;
import org.openbpm.sys.api.model.DefaultIdentity;
import org.openbpm.sys.api.model.SysIdentity;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component("etechFormFieldUserPluginExecutor")
@Primary
// @ConditionalOnMissingClass({"org.openbpm.bpm.plugin.usercalc.formfield.executer.FormFieldUserPluginExecutor"})
@Slf4j
public class FormFieldUserPluginExecutor extends AbstractUserCalcPlugin<FormFieldUserPluginDef> {
    @Resource
    GroupService groupService;

    @Resource
    EtechUserService userService1;

    @Resource
    EtechBpmScript etechBpmScript;

    public List<SysIdentity> queryByPluginDef(BpmUserCalcPluginSession pluginSession, FormFieldUserPluginDef relDef) {
        String identityType = relDef.getIdentityType();
        List<String> ids = queryIds(pluginSession, relDef.getFormFieldPath());

        System.out.println(identityType + " >>> " + ids);

        List<SysIdentity> identity = new ArrayList<>();
        if (ids == null){
            return Collections.emptyList();
        }

        if ("userId".equals(identityType)){
            identity = new ArrayList<>(etechBpmScript.constructeIdentityUsersFromSpliceUserid(ids.get(0)));
            System.out.println(identity);
            return identity;
        }

        for (String id : ids) {
            if (StringUtil.isEmpty(id)){
                continue;
            }

            if ("userAccount".equals(identityType)) {
                IUser user = this.userService1.getUserByAccount(id);
                if (user != null)
                    identity.add(new DefaultIdentity(user));
                continue;
            }
            if ("userId".equals(identityType)) {
                IUser user = this.userService1.getUserById(id);
                System.out.println(user);
                if (user != null){
                    System.out.println(user);
                    identity.add(new DefaultIdentity(user));
                }
                continue;
            }
            IGroup group = this.groupService.getById(identityType, id);
            if (group != null){
                identity.add(new DefaultIdentity(group.getGroupId(), group.getGroupName(), group.getGroupType()));
            }

        }
        if (log.isTraceEnabled()){
            log.info("{} {}{}{}", new Object[] { pluginSession.getBpmInstance().getDefName(), Integer.valueOf(identity.size()), JSON.toJSONString(relDef), JSON.toJSONString(identity) });
        }

        System.out.println(identity);

        return identity;
    }

    List<SysIdentity> queryIdentsByGroup(List<? extends IGroup> groups) {
        List<SysIdentity> identitys = new ArrayList<>();
        for (IGroup group : groups) {
            identitys.add(new DefaultIdentity(group.getGroupId(), group.getGroupName(), group.getGroupType()));
        }
        return identitys;
    }

    private List<String> queryIds(BpmUserCalcPluginSession pluginSession, String formFieldPath) {
        if (StringUtil.isEmpty(formFieldPath) || formFieldPath.indexOf(".") == -1)
            return null;
        String[] formFieldPathArr = formFieldPath.split("\\.");
        IBusinessData businessData = (IBusinessData)pluginSession.getBoDatas().get(formFieldPathArr[0]);
        if (businessData == null) {
            log.warn("{} {}", pluginSession.getBpmInstance().getDefName(), formFieldPath);
            return null;
        }
        if (formFieldPathArr.length == 2) {
            String ids = businessData.getString(formFieldPathArr[1]);
            if (StringUtil.isNotEmpty(ids)) {
                String[] arr = ids.split("\\.");
                return CollectionUtil.newArrayList((String[])arr);
            }
        }
        List<IBusinessData> subTable = businessData.getChild(formFieldPathArr[1]);
        if (CollectionUtil.isEmpty(subTable)) {
            log.info("{} {}", pluginSession.getBpmInstance().getDefName(), formFieldPath);
            return null;
        }
        List<String> orgIds = new ArrayList<>();
        for (IBusinessData subData : subTable) {
            String orgId = subData.getString(formFieldPathArr[2]);
            if (StringUtil.isEmpty(orgId))
                continue;
            String[] ids = orgId.split(",");
            for (String id : ids) {
                if (StringUtil.isNotEmpty(id))
                    orgIds.add(id);
            }
        }
        if (orgIds.size() == 0) {
            log.info("{} {}", pluginSession.getBpmInstance().getDefName(), formFieldPath);
            return null;
        }
        return orgIds;
    }
}
